<template>
  <div class="app-container">
    <div id="map"></div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="门店名称" prop="storeName">
        <el-input
          v-model="queryParams.storeName"
          placeholder="请输入门店名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="联系电话" prop="phoneNumber">
        <el-input
          v-model="queryParams.phoneNumber"
          placeholder="请输入联系电话"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <!-- <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:store:add']"
        >新增</el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:store:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:store:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:store:export']"
        >导出</el-button>
      </el-col> -->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="storeList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="storeName" />
      <el-table-column label="订单号" align="center" prop="longitude" />
      <el-table-column
        label="通用区域"
        align="center"
        prop="phoneNumber"
        width="120"
      />
      <el-table-column label="归属门店" align="center" prop="regionName" />
      <el-table-column label="技师姓名" align="center" prop="detail" />
      <el-table-column label="描述" align="center" prop="longitude" />
      <el-table-column label="状态" align="center" prop="detail" />
      <!-- <el-table-column label="折扣价" align="center" prop="longitude" />
       <el-table-column label="提成金额" align="center" prop="detail" />
       <el-table-column label="排列" align="center" prop="longitude" />
       <el-table-column label="上架" align="center" prop="sex">
        <template slot-scope="scope">
         <span >{{ scope.row.sex=='0'?'男':'女' }}</span>
        </template>
       </el-table-column> -->
      <el-table-column label="创建时间" align="center" prop="intro" />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="250"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:store:edit']"
            >详情</el-button
          >
          <!-- <el-button size="mini" type="text" icon="el-icon-upload2" @click="handleGround(scope.row,statue=1)"
            v-hasPermi="['system:technology:edit']" :disabled="scope.row.statue===1">上架</el-button>
          <el-button size="mini" type="text" icon="el-icon-download" @click="handleGround(scope.row,statue=0)"
            v-hasPermi="['system:technology:remove']" :disabled="scope.row.statue===0">下架</el-button> -->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:store:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改门店对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        label-width="80px"
        v-if="formFlag"
      >
        <el-form-item label="区域名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入区域名称" />
        </el-form-item>
        <!-- <el-form-item label="项目图片" prop="img">
          <image-upload v-model="form.img" />
        </el-form-item> -->

        <el-form-item label="类型" prop="regionId">
          <el-select clearable v-model="form.regionId" @change="changeRegion">
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <el-form-item label="归属门店" prop="regionId">
          <el-select clearable v-model="form.regionId" @change="changeRegion">
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="收支名称" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入包间名称" />
        </el-form-item> -->
        <!-- <el-form-item label="会员价" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入包间名称" />
        </el-form-item> -->
        <!-- <el-form-item label="提成金额" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入包间名称" />
        </el-form-item> -->
        <el-form-item label="状态" prop="regionId">
          <el-select clearable v-model="form.regionId" @change="changeRegion">
            <el-option
              v-for="(item, index) of region"
              :key="index"
              :label="item.value"
              :value="item.key"
              >{{ item.value }}</el-option
            >
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="排序" prop="storeName">
          <el-input v-model="form.storeName" placeholder="请输入包间名称" />
        </el-form-item> -->
      </el-form>
      <el-descriptions title="" v-else :column="2">
        <el-descriptions-item label="用户名">kooriookami</el-descriptions-item>
        <el-descriptions-item label="手机号">18100000000</el-descriptions-item>
        <el-descriptions-item label="居住地">苏州市</el-descriptions-item>
        <el-descriptions-item label="备注">
          <el-tag size="small">学校</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="联系地址"
          >江苏省苏州市吴中区吴中大道 1188 号</el-descriptions-item
        >
      </el-descriptions>
      <div slot="footer" class="dialog-footer" v-if="formFlag">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listStore,
  getStore,
  delStore,
  addStore,
  updateStore,
  listChina,
  listResetPwd,
  listregion,
} from "@/api/system/store";

export default {
  name: "Store",
  data() {
    return {
      formFlag: false,
      map: null,
      local: null,
      mk: null,
      latitude: "",
      longitude: "",
      keyWords: "",
      result: "",
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门店表格数据
      storeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      options: [],
      List: [
        {
          key: 1,
          value: "营业中",
        },
        {
          key: 2,
          value: "未营业",
        },
      ],
      region: [],
    };
  },
  created() {
    this.getList();
    this.listChina();
    this.listregion();
  },
  mounted() {
    this.initMap();
  },
  methods: {
    listregion() {
      listregion().then((res) => {
        this.region = res.data.map((rItem) => {
          return {
            key: rItem.id,
            value: rItem.regionName,
          };
        });
      });
    },
    changeRegion(value) {
      const selectedOption = this.region.find((item) => item.key === value);
      const selectedKey = selectedOption.key;
      const selectedValue = selectedOption.value;
      this.form.regionName = selectedValue;
    },
    initMap() {
      this.map = new BMap.Map("map");
      let point = new BMap.Point(116.404, 39.915);
      this.map.centerAndZoom(point, 12);
      this.map.enableScrollWheelZoom(true); // 开启鼠标滚轮缩放
      this.map.addControl(new BMap.NavigationControl());
    },
    // 点击定位-定位到当前位置
    fixedPos() {
      const _this = this;
      const geolocation = new BMap.Geolocation();
      this.confirmLoading = true;
      geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
          _this.handleMarker(_this, r.point);
          let myGeo = new BMap.Geocoder();
          myGeo.getLocation(
            new BMap.Point(r.point.lng, r.point.lat),
            function (result) {
              _this.confirmLoading = false;
              if (result) {
                _this.latitude = result.point.lat;
                _this.longitude = result.point.lng;
              }
            }
          );
        } else {
          _this.$message.error("failed" + this.getStatus());
        }
      });
    },
    // 搜索地址
    setPlace() {
      this.local = new BMap.LocalSearch(this.map, {
        onSearchComplete: this.searchPlace,
      });
      this.local.search(this.form.detail);
    },
    searchPlace() {
      if (this.local.getResults() != undefined) {
        this.map.clearOverlays(); //清除地图上所有覆盖物
        if (this.local.getResults().getPoi(0)) {
          let point = this.local.getResults().getPoi(0).point; //获取第一个智能搜索的结果
          this.map.centerAndZoom(point, 18);
          this.handleMarker(this, point);
          console.log("经度：" + point.lng + "--" + "纬度" + point.lat);
          this.form.longitude = point.lng;
          this.form.latitude = point.lat;
          this.latitude = point.lat;
          this.longitude = point.lng;
        } else {
          this.$message.error("未匹配到地点!");
        }
      } else {
        this.$message.error("未找到搜索结果!");
      }
    },
    // 设置标注
    handleMarker(obj, point) {
      obj.mk = new BMap.Marker(point);
      obj.map.addOverlay(obj.mk);
      obj.mk.enableDragging(); // 可拖拽
      obj.mk.addEventListener("dragend", function (e) {
        // 监听标注的拖拽，获取拖拽后的经纬度
        this.latitude = point.lat;
        this.longitude = point.lng;
      });
      obj.map.panTo(point);
    },
    listChina() {
      listChina().then((res) => {
        this.options = res.data.map((rItem) => {
          return {
            value: rItem.id,
            label: rItem.cityName,
            children: rItem.children.map((item) => {
              return {
                value: item.id,
                label: item.cityName,
                children: item.children.map((stem) => {
                  return {
                    value: stem.id,
                    label: stem.cityName,
                  };
                }),
              };
            }),
          };
        });
      });
    },
    handleChange() {
      console.log(this.form.province, 123);
    },
    blurDetail() {
      const geocoder = new BMap.Geocoder();
      geocoder.getPoint(
        this.form.detail,
        (point) => {
          if (point) {
            this.result = `经度：${point.lng}，纬度：${point.lat}`;
          } else {
            this.result = "地址解析失败";
          }
        },
        "北京市"
      );
    },
    /** 查询门店列表 */
    getList() {
      this.loading = true;
      listStore(this.queryParams).then((response) => {
        this.storeList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        storeName: null,
        phoneNumber: null,
        province: null,
        provinceString: null,
        city: null,
        cityString: null,
        county: null,
        countyString: null,
        detail: null,
        longitude: null,
        latitude: null,
        intro: null,
        images: null,
        status: null,
        isInitiate: null,
        openingTime: null,
        closingTime: null,
        createTime: null,
        updateTime: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.formFlag = true;
      this.title = "新增收支";
    },
    // 上下架
    handleGround(row, statue) {
      const params = {
        id: row.id,
        statue: statue,
      };
      this.$confirm(
        `此操作将${statue === 1 ? "上架" : "下架"}该数据, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          updateCase(params).then((res) => {
            this.$message({
              type: "success",
              message: `${statue === 1 ? "上架" : "下架"}成功!`,
            });
            this.getList();
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消上下架",
          });
        });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      this.formFlag = false;
      getStore(id).then((response) => {
        // this.form = response.data;
        this.open = true;
        this.title = "评价详情";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateStore(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addStore(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    handReset(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认重置门店编号为"' + ids + '"的数据项？')
        .then(function () {
          return listResetPwd({ userId: ids });
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("重置成功");
        })
        .catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除编号为"' + ids + '"的数据项？')
        .then(function () {
          return delStore(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "system/store/export",
        {
          ...this.queryParams,
        },
        `store_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
